import { Message, useData } from 'magic-ui-react'
import { useEffect, useRef, useState } from 'react'
import jsQR, { QRCode } from "jsqr"
import styles from './styles.module.less'
const Content = () => {
  const videoRef = useRef<HTMLVideoElement>(null)
  const canvasRef = useRef<HTMLCanvasElement>(null)
  const data = useData<{
    tracks: MediaStreamTrack[],
    context: CanvasRenderingContext2D | null,
    interval: NodeJS.Timer | null
  }>({
    tracks: [],
    context: null,
    interval: null
  })
  const [code, setCode] = useState('');

  const start = async () => {
    try {
      // 获取媒体流
      const stream = await navigator.mediaDevices.getUserMedia({
        video: true,
        audio: false
      })
      data.tracks = stream.getTracks()

      if (videoRef.current) {
        videoRef.current.src = stream as any;
        videoRef.current.srcObject = stream;
        await videoRef.current.play();
        run()
      }
    } catch (error) {
      Message.error('您的浏览器暂不支持此功能')
    }
  }

  const run = () => {
    try {
      if (!canvasRef.current || !videoRef.current) {
        return
      }
      data.context = canvasRef.current.getContext('2d');

      const height = videoRef.current.videoHeight
      const width = videoRef.current.videoWidth

      canvasRef.current.width = width
      canvasRef.current.height = height

      if (!data.interval) {
        data.interval = setInterval(() => {
          try {
            data.context?.drawImage(videoRef.current as any, 0, 0, width, height);
            const imageData: any = data.context?.getImageData(0, 0, width, height);
            const code = jsQR(imageData?.data, imageData?.width, imageData?.height);
            if (code) {
              setCode(code.data)
            }
          } catch (error) {
            clearInterval(data.interval as unknown as number)
          }
        }, 200)
      }
    } catch (error) {
      clearInterval(data.interval as unknown as number)
    }
  }

  useEffect(() => {
    start()
  }, [])

  return (
    <div className={styles.Content}>
      <video
        id='vedio'
        ref={videoRef}
        className="h-auto w-full"
      ></video>
      <div className='flex flex-col justify-center items-center flex-1'>
        {code}
      </div>

      <canvas
        style={{
          display: 'none'
        }}
        ref={canvasRef}
      ></canvas>
    </div>
  )
}
export default Content